package cn.edu.sdjzu.xg.bysj.controller;

import cn.edu.sdjzu.xg.bysj.domain.School;
import cn.edu.sdjzu.xg.bysj.exception.BysjException;
import cn.edu.sdjzu.xg.bysj.service.SchoolService;
import cn.edu.sdjzu.xg.bysj.util.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;


//put,http://localhost:8080/SchoolCreate.ctl
@WebServlet("/SchoolCreate.ctl")
public class SchoolCreateCtl extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        JSONObject message_jsonObj = new JSONObject();
        response.setContentType("application/json;charset=UTF-8");
        String req_jsonStr = JSONUtil.getJSON(request);
        //将request body解析成JSONObject对象，可能含有分页信息
        School school = JSON.parseObject(req_jsonStr, School.class);
        try{
            //读取分页信息，形成分页对象
            boolean added = SchoolService.getInstance().add(school);
            message_jsonObj.put("added",added);
            message_jsonObj.put("records",school);
            //分页获得所有学院
            //响应message_jsonObj到前端
            response.getWriter().println(message_jsonObj);
        }catch (BysjException e){
            message_jsonObj.put("message",e.getMessage());
            response.getWriter().println(message_jsonObj);
            e.getStackTrace();
        }catch (SQLException e){
            message_jsonObj.put("message","数据库操作异常");
            response.getWriter().println(message_jsonObj);
            e.getStackTrace();
            message_jsonObj.put("message",e.getMessage());
            response.getWriter().println(message_jsonObj);
        }catch (Exception e){
            message_jsonObj.put("message","网络异常");
            response.getWriter().println(message_jsonObj);
            e.getStackTrace();
            System.out.println(e.getMessage());

        }

    }
}
